package level4.net.web.utils
{
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.net.sendToURL;
	import flash.system.System;

	/**
	 * 用于 http 协议的工具
	 * */
	public class HttpUtil
	{
		public function HttpUtil()
		{
		}
		//设置好 URLRequest.
		private static function setupRequest(url:String,paramObj:Object):URLRequest{
			var args:URLVariables = new URLVariables();
			for(var k:* in paramObj){
				args[k] = encodeURIComponent(paramObj[k]);
			}
			var req:URLRequest = new URLRequest(url);
				req.method = "post";
				req.data = args;
			return req;
		}
		/**
		 * 只发送不接收.
		 * @param url : 请求地址
		 * @param paramObj : 参数对象
		 * */
		public static function sendToUrl(url:String,paramObj:Object):void{
			var req:URLRequest = setupRequest(url,paramObj);
			sendToURL(req);
		}
		/**
		 * 发送数据到http服务器,并获取响应
		 * @param url : 请求地址
		 * @param paramObj : 参数对象
		 * @param onOk : 服务器响应后执行的回调.方法签名:function(resp:String):void.
		 * */
		public static function send(url:String,paramObj:Object,onOk:Function):void{
			var req:URLRequest = setupRequest(url,paramObj);
			var l:URLLoader = new URLLoader(req);
				l.addEventListener(Event.COMPLETE,onComplete);
				
				/////////////////////////
				//闭包
				/////////////////////////
				function onComplete(e:Event):void{
					if(onOk != null){
						onOk(l.data);
					}
				}
		}
		
	}
}